package com.cskaoyan.wordmemorize.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.dao.entity.TopicDelDO;
import com.cskaoyan.wordmemorize.dto.admin.*;
import com.cskaoyan.wordmemorize.request.TopicCommand;
import com.cskaoyan.wordmemorize.request.VocPageRequest;
import com.cskaoyan.wordmemorize.service.TopicService;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/admin/topic")
public class TopicController
{

    @Autowired
    private TopicService topicService;

    // 检查单词是否存在
    @GetMapping("/word")
    public Result<VocDTO> checkWord(@RequestParam String word)
    {
        VocDTO exist = topicService.checkWord(word);
        return Result.ok(exist);
    }

    // 分页获取单选题列表
    @GetMapping("/singleChoice/list")
    public Result<PageDTO<ReviewTopicDTO>> getSingleChoicePage(VocPageRequest vocPageRequest)
    {
        PageDTO<ReviewTopicDTO> singleChoice = topicService.getSingleChoicePage(vocPageRequest);
        return Result.ok(singleChoice);
    }

    // 分页获取选词填空题列表
    @GetMapping("/fillWord/list")
    public Result<PageDTO<ReviewTopicDTO>> getFillWordPage(VocPageRequest vocPageRequest)
    {
        PageDTO<ReviewTopicDTO> fillWord = topicService.getFillWordPage(vocPageRequest);
        return Result.ok(fillWord);
    }

    // 添加题目
    @PostMapping()
    public Result<Void> addTopic(@RequestBody TopicCommand command)
    {
        topicService.addTopic(command);
        return Result.ok();
    }

    // 获取题目详情
    @GetMapping()
    public Result<ReviewTopicDTO> getTopic(@RequestParam Long topicId)
    {
        ReviewTopicDTO detail = topicService.getTopic(topicId);
        return Result.ok(detail);
    }

    // 更新题目
    @PutMapping()
    public Result<Void> updateTopic(@RequestBody TopicCommand command)
    {
        topicService.updateTopic(command);
        return Result.ok();
    }

    // 删除题目
    @DeleteMapping("/{topicId}")
    public Result<DeleteTopicOperateDTO> deleteTopic(
            @PathVariable(value = "topicId") Long topicId,
            @RequestParam(value = "topicType") Integer topicType)
    {
        DeleteTopicOperateDTO delete = topicService.deleteTopic(topicId, topicType);
        return Result.ok(delete);
    }

    @DeleteMapping()
    public Result<DeleteTopicOperateDTO> deleteTopics(
            @RequestBody TopicDelDO ids)
    {
        if (ObjectUtil.isNotEmpty(ids.getIds())){
            ids.getIds().stream().forEach(id -> {
                DeleteTopicOperateDTO delete = topicService.deleteTopic(id, null);
            });
        }
        return Result.ok();
    }


    // 校验Excel中的题目
    @PostMapping("/excel/validation/{type}")
    public Result<Void> topicExcelValidate(
            @PathVariable(value = "type" ,required = false) String type,
            @RequestParam MultipartFile file) throws IOException
    {
        topicService.topicExcelValidate(type, file);
        return Result.ok();
    }

    // Excel添加单选题目
    @PostMapping("/singleChoice")
    public Result<ExcelAddOperateDTO> addSingleChoiceExcel(
            @RequestParam MultipartFile file,
            @RequestParam(value = "employeeId", required = false) Long employeeId) throws IOException
    {
        ExcelAddOperateDTO addSingleChoice = topicService.addSingleChoiceExcel(file, employeeId);
        return Result.ok(addSingleChoice);
    }


    // Excel添加选词填空题
    @PostMapping("/fillWord")
    public Result<ExcelAddOperateDTO> addFillWordExcel(
            @RequestParam MultipartFile file,
            @RequestParam(value = "employeeId", required = false) Long employeeId) throws IOException
    {
        ExcelAddOperateDTO addFillWord = topicService.addFillWordExcel(file, employeeId);
        return Result.ok(addFillWord);
    }

    // 删除选词填空小题
    @DeleteMapping("/subtopic/{id}")
    public Result<DeleteSubTopicOperateDTO> deleteSubTopic(@PathVariable Long id)
    {
        DeleteSubTopicOperateDTO deleteSub = topicService.deleteSubTopic(id);
        return Result.ok(deleteSub);
    }

    // 删除选词填空题的干扰项或者删除单选题选项
    @DeleteMapping("/option/{id}")
    public Result<DeleteTopicOptionOperateDTO> deleteTopicOption(@PathVariable Long id)
    {
        DeleteTopicOptionOperateDTO deleteOption = topicService.deleteTopicOption(id);
        return Result.ok(deleteOption);
    }

    // 下载题目类型对应的Excel模版文件
    @GetMapping("/template/{type}")
    public ResponseEntity<byte[]> downloadTemplate(@Parameter(description = "模版文件类型") @PathVariable("type") String type) throws IOException
    {
        // 使用ClassPathResource读取资源文件

        ClassPathResource resource;

        if ("single".equals(type))
        {
            resource = new ClassPathResource("templates/单选题模版.xlsx");
        } else
        {
            resource = new ClassPathResource("templates/填空题模版.xlsx");
        }
        // 检查文件是否存在
        if (!resource.exists())
        {
            return ResponseEntity.notFound().build();
        }

        // 读取文件内容
        InputStream inputStream = resource.getInputStream();
        byte[] fileBytes = IOUtils.toByteArray(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment",
                URLEncoder.encode(resource.getFilename(), "UTF-8"));

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileBytes);
    }
}
